<?php
class Alllist{
	/**
	 * 数据库对象
	 *
	 * @var Mysql
	 */
	private $db;
	const CACHE_KEY = 'cache_Alllist';
	
	public function __construct($db)
	{
		$this->db = $db;
	}
	
	/**
	 * 添加
	 *
	 * @param unknown_type $id
	 * @param unknown_type $type
	 * @param unknown_type $name
	 * @param unknown_type $seq
	 * @param unknown_type $hidden
	 */
	public function add($type, $name, $seq, $hidden, $isleaf=0)
	{
		$this->db->insert("alllist", array('type' => $type, 'name' => $name, 'seq' => $seq, 'hidden' => $hidden, 'isleaf' => $isleaf));
		
		$this->updateCache($type);
	}
	
	
	/**
	 * 修改
	 *
	 * @param unknown_type $cid
	 * @param array $newvalue
	 */
	public function change($id, array $newvalue)
	{
		$this->db->update("alllist", $newvalue, 'id=' . intval($id));
		$type = $this->db->fetchOne("select type from alllist where id='?'", array($id));
		$this->updateCache($type);
	}
	
	/**
	 * 删除
	 *
	 * @param unknown_type $cid
	 */
	public function delete($id)
	{		
		$type = $this->db->fetchOne("select type from alllist where id='?'", array($id));
		$this->db->delete("alllist", 'id="' . intval($id) . '"');
		$this->updateCache($type);
	}
	
	/**
	 * 根据类型获取分类列表
	 *
	 * @param int $type
	 * @param boolean $isShowHidden	是否显示隐藏分类
	 * @return array
	 */
	public function getAllListByType($type, $isShowHidden = true)
	{
		$result = FileCache::getInstance()->get(self::CACHE_KEY  . $type);
		if ($result == null){
			$arr = $this->db->fetchAll("select * from alllist where type='?' order by seq desc, id asc", array($type));
			$result = array();
			foreach ($arr as $v){
				$result[$v['id']] = $v;
			}
			FileCache::getInstance()->set(self::CACHE_KEY  . $type, $result);
		}
		
		if ($isShowHidden == false){
			foreach ($result as $k => $v){
				if ($v['hidden']){
					unset($result[$k]);
				}
			}
		}
		
		reset ($result);
		
		return $result;
	}
	
	
	/**
	 * 获取第一个分类编号
	 * @param unknown_type $type
	 */
	public function getFirstListTypeId($type)
	{
		$ret = 0;
		$arr_type = $this->getAllListByType($type, false);

		if (count($arr_type) > 0){
			reset($arr_type);
			$ret = key($arr_type);
		}
		
		return $ret;
	}
		
	public function getDetailByID($id)
	{
		return $this->db->fetchRow("select * from alllist where id='?'", array($id));
	}
	
	public function updateCache($type)
	{
		FileCache::getInstance()->delete(self::CACHE_KEY . $type);
		FileCache::getInstance()->delete(self::CACHE_KEY );
	}
}